<?php

/**
 * 供应商银行帐号信息管理
 * Created by PhpStorm.
 * User: z
 * Date: 14-8-30
 * Time: 下午3:18
 */
class Controller_Supplierbank extends Controller_Admin
{
    /**
     * 权限检查
     */
    public function before()
    {
        try{
            ACL::Required('supplier bankinfo view');
        }catch(HTTP_Exception_403 $e){
            Message::error('sorry，你没有权限进这个目录');
            $this->request->redirect(URL::base(TRUE));
        }
        parent::before();
    }

    /**
     * 显示和处理查询信息
     */
    public function action_index()
    {
        $this->title = __("供应商银行帐号信息");

        try{

            $payway_all = Payway::do_select();
            $coins_arr = supplierbank::getCoins_arr();//币种信息

            $condtion = array();

            if(isset($_GET['supplier_id']) and intval($_GET['supplier_id'])>0){
                $condtion['supplier_id'] = intval($_GET['supplier_id']);
            }
            if(isset($_GET['supplier_name']) and trim($_GET['supplier_name'])){
                $condtion['supplier_name'] = trim($_GET['supplier_name']);
            }
            if(isset($_GET['payways_id']) and intval($_GET['payways_id'])>0){
                $condtion['payways_id'] = intval($_GET['payways_id']);
            }
            if(isset($_GET['active_status']) and intval($_GET['active_status'])>0){
                $condtion['active_status'] = intval($_GET['active_status']);
            }
            if(isset($_GET['check_status']) and intval($_GET['check_status'])>0){
                $condtion['check_status'] = intval($_GET['check_status']);
            }
            if(isset($_GET['coinid']) and intval($_GET['coinid'])>0){
                $condtion['coinid'] = intval($_GET['coinid']);
            }

            if(isset($_GET['bankname']) and trim($_GET['bankname'])){
                $condtion['bankname'] = trim($_GET['bankname']);
            }
            if(isset($_GET['bankaccount']) and trim($_GET['bankaccount'])){
                $condtion['bankaccount'] = trim($_GET['bankaccount']);
            }
            if(isset($_GET['bankaccountname']) and trim($_GET['bankaccountname'])){
                $condtion['bankaccountname'] = trim($_GET['bankaccountname']);
            }
            $count      = count(Supplierbank::do_select($condtion));
            $pagination = Pagination::factory(array(
                'items_per_page' => 20,
                'total_items'    => $count,
                'uri'            => $this->request->uri(),
            ));

            $condtion['limit']  = $pagination->items_per_page;
            $condtion['offset'] = $pagination->_offset;

            $re_lists = Supplierbank::do_select($condtion);
            $re_lists = Supplierbank::datas_to_views($re_lists);
        }catch(Database_Exception $e){
            $re_lists = NULL;
            Message::error('系统出错,请联系IT！');
        }

        $view = View::factory('supplierbank/index');
        $view->set('payway_all',$payway_all);
        $view->set('re_lists',$re_lists);
        $view->set('condtion',$condtion);
        $view->set('pagination',$pagination);
        $view->set('coins_arr',$coins_arr);
        $this->response->body($view);
    }

    /**
     * 显示添加信息
     * 添加一下信息
     * 付款方式
     * 开户银行
     * 银行账户
     * 银行帐号
     */
    public function action_add()
    {

        /**
         * 没有权限
         */
        if(!ACL::check('supplier bankinfo edit')){
            $this->request->redirect('supplier/supplierbank/index');
        }

        $this->title = __("添加供应商银行帐号信息");

        try{
            $payways_all = Payway::get_payway_lists_active();
        }catch(Database_Exception $e){
            Message::error('系统出错,请联系IT！');
            $this->request->redirect('');
        }

        $view = View::factory('supplierbank/add');
        $view->set('payways_all',$payways_all);
        $view->set('add_id',isset($re)?$re:NULL);
        //$view->set('coins', supplierbank::getCoins_arr());
        $this->response->body($view);
    }

    /**
     * 添加信息
     */
    public function action_doadd()
    {
        if(!ACL::check('supplier bankinfo edit')){
            //$this->request->redirect('supplier/supplierbank/index');
            $notice ='您没有权限操作，请联系管理员';
        }
//供应商二次代码修改
//        if(isset($_POST["supplier_id"])){
//
//            $payaccountinfo = $supplierpayaccount = array();
//            $time = date("Y-m-d H:i:s");
//            $supplierpayaccount ['supplier_id']    = intval($_POST["supplier_id"]);
//            $supplierpayaccount['payways_id']     = intval($_POST["payways_id"]);
//            $supplierpayaccount['check_status'] = 1;
//            $supplierpayaccount['active_status'] = 1;
//
//            $payaccountinfo['bankname']       = trim($_POST["bankname"]);
//            $payaccountinfo['bankaccount']     = trim($_POST["bankaccount"]);
//            $payaccountinfo['bankaccountname'] = trim($_POST["bankaccountname"]);
//            $payaccountinfo['createtime'] = $payaccountinfo['updatetime'] = $time;
//            try{
//                list($supplierpayaccount['payaccountinfo_id'],) = DB::insert('payaccountinfo',array_keys($payaccountinfo))
//                    ->values(array_values($payaccountinfo))
//                    ->execute('newerp');
//
//                if($supplierpayaccount['payaccountinfo_id'] > 0)
//                {
//                      list($supplierpayaccount_id,) = DB::insert('supplierpayaccount',array_keys($supplierpayaccount))
//                          ->values(array_values($supplierpayaccount))
//                          ->execute('newerp');
//                    if($supplierpayaccount_id > 0)
//                    {
//                         Message::success('添加成功');
//                         $this->request->redirect('supplier/supplierbank/detail?id='.$supplierpayaccount_id);
//                    }
//                    else
//                    {
//                        Message::error('添加失败');
//                    }
//                }
//            }catch(Database_Exception $e){
//                Message::error('系统出错,请联系IT！');
//            }
//        }
//$this->request->redirect('supplier/supplierbank/add');
        $payaccountinfo = $supplierpayaccount = array();
        $time = date("Y-m-d H:i:s");
        $payaccountinfo['createtime'] = $time;
        $payaccountinfo['coinid'] = $_POST["currency_account_id"];
        $bank_info = json_decode($_POST['bank_info'],true);


        $supplierpayaccount ['supplier_id']    = $bank_info["supplier_id"];
        $supplierpayaccount['payways_id']     = $bank_info["payways_id"];
        $supplierpayaccount['check_status'] = 1;
        $supplierpayaccount['active_status'] = 1;
        $supplierpayaccount['createtime']   = $time;

        //供应商二次代码新增
        if($_POST['currency_account_id']==1){//人名币数组
            $payaccountinfo['bankname']        = $bank_info["bankname_RMB"];
            $payaccountinfo['bankaccount']     = $bank_info["bankaccount_RMB"];
            $payaccountinfo['bankaccountname'] = $bank_info["bankaccountname_RMB"];

        }else{//外币数组
            $payaccountinfo['bankname']        = $bank_info["bankname_USD"];
            $payaccountinfo['banklocation']    = $bank_info["banklocation_USD"];
            $payaccountinfo['bankaddress']     = $bank_info["payee_bankaccount_address_USD"];
            $payaccountinfo['bankaccountname'] = $bank_info["payee_name_USD"];
            $payaccountinfo['bankaccount']     = $bank_info["payee_bankaccount_num"];
            $payaccountinfo['bankmanaddress']  = $bank_info["payee_address_USD"];
            $payaccountinfo['bankswift']       = $bank_info["payee_bankaccount_code_USD"];

        }
            list($supplierpayaccount['payaccountinfo_id'],) = DB::insert('payaccountinfo',array_keys($payaccountinfo))
                ->values(array_values($payaccountinfo))
                ->execute('newerp');

            if($supplierpayaccount['payaccountinfo_id'] > 0)
            {
                list($supplierpayaccount_id,) = DB::insert('supplierpayaccount',array_keys($supplierpayaccount))
                    ->values(array_values($supplierpayaccount))
                    ->execute('newerp');
                if($supplierpayaccount_id > 0)
                {
//                    Message::success('添加成功');
//                    $this->request->redirect('supplier/supplierbank/detail?id='.$supplierpayaccount_id);
                    $notice = $supplierpayaccount_id;
                }
                else
                {
                   $notice = "添加失败";
                }
            }
        echo $notice;exit;
    }

    /**
     * 在添加供应商的银行帐号信息是获取供应商提示信息
     */
    public function action_getsupplierinfo()
    {
    }

    /**
     * 显示/修改信息
     * 可以修改
     * 付款方式
     * 开户银行
     * 银行账户
     * 银行帐号
     */
    public function action_edit()
    {
        $this->title = __("修改供应商银行帐号信息");

        if(!ACL::check('supplier bankinfo edit')){
            $this->request->redirect('supplier/supplierbank/index');
        }
        if(isset($_GET['id']) and intval($_GET['id'])>0){
            try{
                $payways_all = Payway::get_payway_lists_active();
                $datail_data = Supplierbank::do_select(array('id' => trim($_GET['id'])));
                $datail_data = Supplierbank::datas_to_views($datail_data);

                if(empty($datail_data) or !isset($datail_data[0]['id'])){
                    Message::error('查询不到数据');
                    $this->request->redirect('supplier/supplierbank/index');
                }
            }catch(Database_Exception $e){
                Message::error('系统出错,请联系IT！');
                $this->request->redirect('supplier/supplierbank/index');
            }
        }

        $view = View::factory('supplierbank/edit');
        $view->set('detail_data',isset($datail_data[0])?$datail_data[0]:NULL);
        $view->set('payways_all',$payways_all);
        $this->response->body($view);
    }

    /**
     *
     */
    public function action_doedit()
    {

        if($this->request->is_post()
            and isset($_POST['edit_submit'])
        ){
            try{


            $supplierpayaccount = $payaccountinfo =  array();
            $time = date('Y-m-d H:i:s');
            $payaccountinfo_id = trim($_POST['payaccountinfo_id']);

            $payaccountinfo['bankname']         = isset($_POST['bankname'])?trim($_POST['bankname']):'';//开户银行/收款银行名称
            $payaccountinfo['banklocation']     = isset($_POST['banklocation'])?trim($_POST['banklocation']):'';//收款银行地区
            $payaccountinfo['bankaccount']      = isset($_POST['bankaccount'])?trim($_POST['bankaccount']):'';//帐号/收款人账户号码/IBAN
            $payaccountinfo['bankaccountname']  = isset($_POST['bankaccountname'])?trim($_POST['bankaccountname']):'';//帐户名/收款人名称
            $payaccountinfo['bankaddress']      = isset($_POST['bankaddress'])?trim($_POST['bankaddress']):'';//收款银行地址
            $payaccountinfo['bankmanaddress']   = isset($_POST['bankmanaddress'])?trim($_POST['bankmanaddress']):'';//收款人地址
            $payaccountinfo['bankswift']        = isset($_POST['bankswift'])?trim($_POST['bankswift']):'';//银行代码SWIFT
            $payaccountinfo['coinid']           = isset($_POST['coinid'])?trim($_POST['coinid']):1;//帐号币种


                $payaccountinfo_old = DB::select('id','bankname','banklocation','bankaccountname','bankaccount','bankaddress','bankmanaddress','bankswift')
                ->from('payaccountinfo')
                ->where('id','=',$payaccountinfo_id)
                ->execute('newerp')
                ->current();

             if($payaccountinfo_old
             and isset($payaccountinfo_old['id']))
            {
                /**
                 * 发生改变
                 */
                if(($payaccountinfo_old['bankname'] != $payaccountinfo['bankname'])
                 or ($payaccountinfo_old['banklocation'] != $payaccountinfo['banklocation'])
                 or ($payaccountinfo_old['bankaccount'] != $payaccountinfo['bankaccount'])
                 or ($payaccountinfo_old['bankaccountname'] != $payaccountinfo['bankaccountname'])
                 or ($payaccountinfo_old['bankaddress'] != $payaccountinfo['bankaddress'])
                 or ($payaccountinfo_old['bankmanaddress'] != $payaccountinfo['bankmanaddress'])
                 or ($payaccountinfo_old['bankswift'] != $payaccountinfo['bankswift']))
                 {

                     $payaccountinfo['createtime']  = $time;

                     DB::update('payaccountinfo')
                         ->set(array('isuse'=>0,'updatetime'=>date('Y-m-d H:i:s')))//更新时更新时间有
                         ->where('id','=',$payaccountinfo_id)
                         ->execute('newerp');

                     list($payaccountinfo_ok,)=DB::insert('payaccountinfo')
                         ->columns(array_keys($payaccountinfo))//插入时没有更新时间默认是0
                         ->values($payaccountinfo)
                         ->execute('newerp');

                     $supplier_old = DB::select('id','supplier_id')->from('supplierpayaccount')
                         ->where('id','=',$_POST['id'])
                         ->limit(1)
                         ->execute('newerp')
                         ->current();
                     if($supplier_old)
                     {
                        DB::update('supplierpayaccount')->set(array('active_status'=>9,'updatetime'=>date('Y-m-d H:i:s')))
                            ->where('id','=',$supplier_old['id'])
                            ->execute('newerp');
                         $supplier = array();
                         $supplier['supplier_id'] = isset($supplier_old['supplier_id'])?$supplier_old['supplier_id']:'';
                         $supplier['payways_id'] = $_POST['payways_id'];
                         $supplier['payaccountinfo_id'] = $payaccountinfo_ok;
                         $supplier['active_status'] = 1;
                         $supplier['check_status'] = 1;
                         $supplier['check_remark'] = '';
                         $supplier['createtime'] = $time;
                         //$supplier['updatetime'] = $time;
                         $supplier['check_id'] = User::active_user()->id;
                         list($supplierpayaccount_ok,)=DB::insert('supplierpayaccount')->columns(array_keys($supplier))
                             ->values($supplier)
                             ->execute('newerp');
                     }

                 }else{
                    $supplier_old = DB::select('id','supplier_id','payways_id')->from('supplierpayaccount')
                        ->where('id','=',$_POST['id'])
                        ->limit(1)
                        ->execute('newerp')
                        ->current();
                    if($supplier_old&&$_POST['payways_id']!=$supplier_old['payways_id'])
                    {
                        $supplier = array();
                        $supplier['payways_id'] = $_POST['payways_id'];
                        $supplier['updatetime'] = $time;//有更新时间
                        $supplier['check_status'] = 1;//待审核状态
                        $supplier['check_id']   = User::active_user()->id;

                        $supplierpayaccount_ok=DB::update('supplierpayaccount')->set($supplier)
                            ->where('id','=',$supplier_old['id'])
                            ->execute('newerp');

                        if($supplierpayaccount_ok==1)$supplierpayaccount_ok = $supplier_old['id'];
                    }
                }
            }

                if($payaccountinfo_ok or $supplierpayaccount_ok){
                    Message::success('修改成功');
                    $this->request->redirect('supplier/supplierbank/detail?id='.$supplierpayaccount_ok);
                }else{
                    Message::error('修改失败');
                    $this->request->redirect('supplier/supplierbank/edit?id='.$_POST['id']);
                }
            }catch(Database_Exception $e){
                Message::error('系统出错,请联系IT！');
                $this->request->redirect('supplier/supplierbank/index');
            }
        }else{
            $this->request->redirect('supplier/supplierbank/index');
        }
    }

    /**
     * 显示一个供应商的银行帐号信息详情
     */
    public function action_detail()
    {
        $this->title = __("供应商银行帐号信息");

        if($this->request->is_get() and isset($_GET['id']) and intval($_GET['id'])>0){

            try{
                $datail_data = Supplierbank::do_select(array('id' => trim($_GET['id'])));
                $datail_data = Supplierbank::datas_to_views($datail_data);

                if(empty($datail_data)){
                    Message::error('查询不到数据');
                    $this->request->redirect('supplier/supplierbank/index');
                }
            }catch(Database_Exception $e){
                Message::error('系统出错,请联系IT！');
                $this->request->redirect('supplier/supplierbank/index');
            }
        }else{
            Message::error('查询不到数据');
            $this->request->redirect('supplier/supplierbank/index');
        }

        $view = View::factory('supplierbank/detail');
        $view->set('detail_data',isset($datail_data[0])?$datail_data[0]:NULL);
        $this->response->body($view);
    }

    /**
     * 处理变更状态信息
     * 激活/停用
     */
    public function action_changestatus()
    {
        $re = array(
            'code' => 0,
            'msg'  => '操作失败'
        );

        if($this->request->is_ajax()){
            try{
                $up_datas                     = array();
                $up_datas['id']               = intval($_POST['id']);
                $up_datas['active_status']    = intval($_POST['active_status']);

                /*$up_datas['payaccountinfo_id'] = intval($_POST['payaccountinfo_id']);*/
                $re_ok = DB::update('supplierpayaccount')
                    ->set(array('active_status'=>$up_datas['active_status'],'updatetime'=>date("Y-m-d H:i:s")))
                    ->where('id','=',$up_datas['id'])
                    ->execute('newerp');

                if($re_ok){
                    $re['code'] = 1;
                    $re['msg']  = '操作成功';
                }
            }catch(Database_Exception $e){
                $re['code'] = 9;
                $re['msg']  = '系统出错,请联系IT！';
            }
        }

        echo json_encode($re);
        exit;
    }

}